<html>
<head>
<title>Passing MessagePort to a SharedWorker</title>
<script src="worker_utils.js"></script>
<script>
function log(message)
{
  document.getElementById("result").innerHTML += message + "<br>";
}

var worker = null;
var message_channel = null;

function do_test() {
  worker = new SharedWorker("messageport_worker.js");
  worker.port.onmessage = process_message_from_worker;
  // It's crucial for this test that we don't wait for the worker to be connected
  // before posting the message.
  log("Sending a port to the worker.");
  message_channel = new MessageChannel();
  worker.port.postMessage({message: "Sending a port.",
                           port: message_channel.port2},
                          [message_channel.port2]);
}

function process_message_from_worker(event) {
    log("Message from worker: " + event.data);
    if (event.data == "Worker got a port.") {
      // Communicate with the worker via the message channel.
      message_channel.port1.onmessage = function (event) {
        log("Message from worker (via channel): " + event.data);
        if (event.data == "Worker got a message via the passed port.")
          onSuccess();
        else
          onFailure();
      };
      message_channel.port1.start();
      log("Sending a message to the worker via the channel.");
      message_channel.port1.postMessage({message: "Message via the channel."});
   }
}

</script>
</head>
<body onload="do_test()">
<div id=statusPanel></div>
<div id=result></div>
</body>
</html>
